<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="15">
        <el-col :span="4">
          <el-input
            v-model="listQuery.search"
            placeholder="模糊搜索"
            style="width: 200px;"
            size="small"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          ><i slot="prefix" class="el-input__icon el-icon-search" /></el-input>
        </el-col>
        <el-col :span="4">
          <el-button class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFilter">
            搜索
          </el-button>
          <el-button
            v-if="checkPermission(['admin','tags_create','tags_all'])"
            class="filter-item"
            size="small"
            style="margin-left: 10px;"
            type="primary"
            icon="el-icon-edit"
            @click="handleCreate"
          >新增</el-button>
        </el-col>
        <el-col :span="4" :offset="12">
          <el-button-group>
            <el-tooltip content="支持先筛选后再导出哦">
              <el-button size="small" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
                导出
              </el-button>
            </el-tooltip>
            <el-button size="small" class="filter-item" type="primary" icon="el-icon-upload" @click="handleUpload">
              导入
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
    </div>
    <!--表格渲染-->
    <el-table v-if="checkPermission(['admin','tags_list','tags_all'])" v-loading="listLoading" :data="list" border size="small" row-key="id">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="数据库">
              <span>{{ props.row.database }}</span>
            </el-form-item>
            <el-form-item label="补丁">
              <span>{{ props.row.patch }}</span>
            </el-form-item>
            <el-form-item label="联系人">
              <span>{{ props.row.contact }}</span>
            </el-form-item>
            <el-form-item label="开发商">
              <span>{{ props.row.developers }}</span>
            </el-form-item>
            <el-form-item label="创建日期">
              <span>{{ props.row.create_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
            <el-form-item label="上次更新">
              <span>{{ props.row.update_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.remarks }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center" width="175%">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="servers" label="服务器" align="left" width="145%">
        <template slot-scope="scope">
          <template v-for="tag in scope.row.servers.split('\n')">
            <el-tag v-if="scope.row.servers != ''" :key="tag.id" type="danger" size="small" style="margin:5px;">{{ tag }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="port" label="端口" align="left" width="300%">
        <template slot-scope="scope">
          <template v-for="tag in scope.row.port.split('\n')">
            <el-tag v-if="scope.row.port != ''" :key="tag.id" type="success" size="small" style="margin:5px;">{{ tag }}</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="environment" label="环境" align="center" width="100%">
        <template slot-scope="scope">
          <span v-if="scope.row.environment=='正式'" style="color:#67C23A;">
            <svg-icon slot="prefix" style="height:1.5em;width:1.5em;" icon-class="env" />
            {{ scope.row.environment }}
          </span>
          <span v-if="scope.row.environment=='测试'" style="color:#909399;">
            <svg-icon slot="prefix" style="height:1.5em;width:1.5em;" icon-class="env_test" />
            {{ scope.row.environment }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="f5_url" label="F5地址" align="center" width="180%">
        <template slot-scope="scope">
          <span>{{ scope.row.f5_url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="190%" align="center">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['admin','tags_edit','tags_all'])" type="primary" size="mini" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-if="checkPermission(['admin','tags_delete','tags_all'])" slot="reference" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600px">
      <el-form ref="dataForm" :model="form" size="small" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="名称" />
        </el-form-item>
        <el-form-item label="环境" prop="environment">
          <el-radio-group v-model="form.environment">
            <el-radio-button label="测试" />
            <el-radio-button label="正式" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="联系人" />
        </el-form-item>
        <el-form-item label="开发商" prop="contact">
          <el-input v-model="form.developers" placeholder="开发商" />
        </el-form-item>
        <el-form-item label="服务器" prop="servers">
          <el-input v-model="form.servers" placeholder="服务器" type="textarea" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="端口" type="textarea" />
        </el-form-item>
        <el-form-item label="F5地址" prop="f5_url">
          <el-input v-model="form.f5_url" placeholder="F5地址" />
        </el-form-item>
        <el-form-item label="数据库" prop="database">
          <el-input v-model="form.database" placeholder="数据库" />
        </el-form-item>
        <el-form-item label="补丁" prop="patch">
          <el-input v-model="form.patch" placeholder="补丁" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" style="width:100%;" rows="2" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import { parseTime } from '@/utils'
import { getMW, addMW, delMW, editMW } from '@/api/middleware'
export default {
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      listLoading: true,
      form: {
        f5_url: '',
        servers: '',
        port: '',
        environment: '',
        database: '',
        developers: '',
        patch: '',
        contact: '',
        name: '',
        remarks: ''
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        servers: [
          { required: true, message: '服务器组不能为空', trigger: 'blur' }
        ]
      },
      listQuery: {
        page: 1,
        limit: 10,
        search: undefined
      },
      columns: [
        {
          text: '名称',
          value: 'name'
        }
      ],
      menus: []
    }
  },
  created() {
    this.$nextTick(() => {
      this.getList()
    })
  },
  methods: {
    checkPermission,
    getList() {
      getMW(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        this.listLoading = false
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 170)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除此行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMW(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetForm() {
      this.form = {
        f5_url: '',
        servers: '',
        port: '',
        environment: '',
        database: '',
        patch: '',
        contact: '',
        name: '',
        remarks: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        // 清除
        this.$refs['dataForm'].resetFields()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addMW(this.form).then(() => {
            this.resetForm()
            // this.list.unshift(this.temp)
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
            this.dialogFormVisible = false
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetForm()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
        this.$refs['dataForm'].clearValidate()
        this.form = { ...row }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editMW(this.form.id, this.form).then(() => {
            for (const v of this.list) {
              if (v.id === this.form.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.form)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.handleFilter()
          })
        }
      })
    },
    handleUpload() {
      this.$router.push({
        path: '/assets/server/upload',
        query: { type: 'middleware' }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      this.$confirm('你可以设置表格页数(如999/页)以展示页数以导出更多数据', '提示', {
        confirmButtonText: '确定导出',
        cancelButtonText: '取消'
      }).then(() => {
        this.$emit('exportLimit')
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['id', '名称', '服务器', '端口', '环境', 'F5地址', '数据库', '补丁', '联系人', '开发商', '备注']
          const filterVal = ['id', 'name', 'servers', 'port', 'environment', 'f5_url', 'database', 'patch', 'contact', 'developers', 'remarks']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'MiddleWareList'
          })
        })
        this.$message({
          type: 'success',
          message: '导出成功!'
        })
      })
      this.downloadLoading = false
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else if (j === 'idc') {
          if (v[j] !== null) {
            return (v[j].name)
          }
        } else if (j === 'tags') {
          if (v[j] !== null) {
            const temp = []
            for (const z of v[j]) {
              temp.push(z.name)
            }
            return temp
          }
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style scoped>
  .console {
    width:100%;
  }
  .term-body {
      background: rgb(0, 0, 0);
      margin:0 0 0 0px!important;
  }
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    color: #99a9bf;
    font-size:12px
  }
  .table-expand span {
    color:#606266;
    font-size:12px
  }
  .el-table .cell {
  white-space: pre-line;
}
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 25%;
  }
</style>
